#!/bin/bash

#
# Initialization
export DRAW_INI=
export DRAW_CFG=
source $DRAW_INI
source $DRAW_CFG

# get command line parameters
while getopts dr:l:p:t: option
do
        case "$option" in
            d) DODEBUG=true;;               # option -d to print out commands
            r) RUN_DIR="$OPTARG";;
            l) LINE="$OPTARG";;
            p)                              # -p 1/2/3 to execute a particular phase, e.g.: -p1 -p2 -p3
              case "$OPTARG" in
                1) DOPHASE1=true;;
                2) DOPHASE2=true;;
                3) DOPHASE3=true;;
                4) DOPHASE4=true;;
                5) DOPHASE5=true;;
                6) DOPHASE6=true;;
              esac;;
            t) TEST_FUNCTION="$OPTARG";;    # execute function e.g.,   -t "stat _merged_nodup_uniq_recal"
        esac
done

#
# Globals
USER=$LOGNAME
export CMD_DIR=$CMD_DRAW
export REF_FASTA=$GENOME_REF
export SNPDB=$DBSNP_REF
export SNPDB_INDELS_ONLY=$DBSNP_REF_INDELS
export TARGET=$TARGETS_FILE
export FLANK=$TARGET_FLANKS_FILE
export SNPEFF=$SNPEFF_DB

export BAM_DIR=../bam
export STAT_DIR=stat
export VCF_DIR=vcf

#
# User Configuration

###DATA_TYPE=(TILESQSEQ | TILESFASTQ | TILESELAND)
###TARGET_COVERAGE=(AGILENT | NIMBLEGEN)

DATA_TYPE=
TARGET_COVERAGE=

#Template variables below
export RG_STR=

export FC=

export mbq=
export mmq=

if [[ $DODEBUG ]]; then
	ls -l $BAM_DIR/*.bam
fi

#
# SUB
SUBCMD=$SUB
[[ $DODEBUG ]] && SUB="echo $SUB"

NUMJOBS=`qstat -u $USER|grep -c $USER`
export SUBARGS="-S /bin/bash -q $GRID_QUEUE -cwd -v DRAW_INI,DRAW_CFG,REF_FASTA,SNPDB -j y -o $STDOUT -hard -l h_stack=256m,h_vmem=1G"

#
# function libraries
source $CMD_DIR/lib/ngs.phase1_lib.pe.sh
source $CMD_DIR/lib/ngs.phase2_lib.pe.sh
source $CMD_DIR/lib/ngs.phase3_lib.pe.sh


if [ ! -z "$TEST_FUNCTION" ]
then
 eval $TEST_FUNCTION
 exit
fi

# Test declared variables and files
draw_test_variables

if [ $draw_test_variables -eq 0 ];then
 echo "Cannot proceed with pipeline"
 exit
elif [ $draw_test_variables -eq 2 ];then
 echo "Continuing with warning"
fi

#############################################################
# PHASE 1 - Create BAM alignments                           #

if [ $DATA_TYPE == "TILESQSEQ" ] && [[ $DOPHASE1 ]]; then
  echo "Phase 1"
  [ $(checkIncompleteFASTQ) == 1 ] && qseqToFastq
  [ $(checkIncompleteSAI) == 1 ]   && bwaAln
  [ $(checkIncompleteSAM) == 1 ]   && bwaSamp
  #[ $(checkIncompleteBAM) == 1 ]   && samToBam
  mergeSamToBam

elif [ $DATA_TYPE == "TILESFASTQ" ] && [[ $DOPHASE1 ]]; then
  echo "Phase 1"
  [ $(checkIncompleteSAI) == 1 ]   && bwaAln
  [ $(checkIncompleteSAM) == 1 ]   && bwaSamp
  mergeSamToBam

elif [ $DATA_TYPE == "ONEFASTQ" ] && [[ $DOPHASE1 ]]; then
  echo "Phase 1"
  bwaAlnOneFastq
  bwaSampOneFastq

fi
###################### EOF PHASE 1 #########################


############################################################
#                                                          #
# PHASE 4 - Merge BAM : the pipeline might start here      #
# the bam files should be local realigned at known Indels  #
if [ $DOPHASE4 ]; then
  echo "Phase 4"
 mergeIndelRealnBam
 dedupNIndexBam mergeIndelRealnBam
 recal

fi
###################### EOF PHASE 4 #########################


############################################################
#                                                          #
# PHASE 2 - BAM Recalibration                              #
if [ $DATA_TYPE != "ONEFASTQ" ] && [[ $DOPHASE2 ]]; then
  echo "Phase 2"

 addReadGroup
 markdup
 doFlagStat markdup "s_${LINE}_merged_rg_markdup"

 if [ -z $DBSNP_REF ];then
    recal "s_${LINE}_merged_rg_markdup"
 else
    localRealignIndel
    recal "s_${LINE}_merged_rg_markdup.indel_realign" 
 fi

# merge_chr_table

elif [ $DATA_TYPE == "ONEFASTQ" ] && [[ $DOPHASE2 ]]; then
  echo "Phase 2"

  sortSamOneFastq
  dedupBamOneFastq

  recal
  merge_chr_table

fi

###################### EOF PHASE 2 #########################


############################################################
#                                                          #
# PHASE 3 - VariantCall and Generate Stats                 #
if [[ $DOPHASE3 ]]; then
	echo "Phase 3 - VariantCall and Generate Stats"

	count=1
	for dir in  ${DATASET[@]};do
		if [[ $DODEBUG ]];then
			echo "ln -s $dir/cmd/*recal.FULL.ba* $BAM_DIR"
		else
			ln -s $dir/cmd/*recal.FULL.ba* "$BAM_DIR" 2>/dev/null
		fi
	done

	variantCallBatch
	if [ ! -z $TARGET ];then #WES
		targetCvgBatch
	fi
	genomeCvgBatch

# collectMetrics
fi

###################### EOF PHASE 3 #########################


############################################################
#                                                          #
# PHASE 5 - populates SneakPeek                            #
if [[ $DOPHASE5 ]]; then
	echo "Phase 5 - populates SneakPeek"
	if [ -s ${LINE}_speek.txt ]; then
    insertSPeek
  else
		echo -e "${LINE}_speek.txt not found or empty."
  fi
fi

###################### EOF PHASE 5 #########################


############################################################
#                                                          #
# PHASE 6 - Additional Analyses                            #

if [ ! -z $TARGETS_FILE ] && [[ $DOPHASE6 ]]; then
    echo "Phase 6"
    target_coverages $TARGETS_FILE $TARGET_COVERAGE
fi

###################### EOF PHASE 6 #########################
